package com.block.channel.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.block.channel.service.IApkInfoService;
import com.block.channel.service.ICountInfoService;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.model.dto.CountInfoDTO;
import com.block.db.entity.ApkInfo;
import com.block.db.mapper.ApkInfoMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2022-08-08
 */
@Service
public class ApkInfoServiceImpl extends ServiceImpl<ApkInfoMapper, ApkInfo> implements IApkInfoService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ICountInfoService countInfoService;

    @Override
    public String getDownloadUrl(String channelCode, String ip) {

        ApkInfo apkInfo = this.baseMapper.getLastApkInfo();
        String downloadUrl = "";
        if (ObjectUtil.isNotEmpty(apkInfo)){
            downloadUrl = apkInfo.getDownloadUr();
        }

        // 3.统计渠道 下载信息
        String redisKey = StrUtil.format(RedisKeyConstant.COUNT_DOWNLOAD_KEY, channelCode, ip);
        boolean result = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, "0", 1L, TimeUnit.DAYS);
        if (result){
            // 3.统计渠道uv信息
            CountInfoDTO countInfoDTO = new CountInfoDTO();
            countInfoDTO.setChannelCode(channelCode);
            countInfoDTO.setDownloadCount(1);
            countInfoService.calculateDataInfo(countInfoDTO);
        }

        return downloadUrl;
    }
}
